//
//  HRNavigationController.swift
//  XMLA
//
//  Created by Gao on 17/2/16.
//  Copyright © 2017年 Odm. All rights reserved.
//

import UIKit
import AVFoundation
import AFNetworking

// 主要作用承载PlayView
class HRNavigationController: UINavigationController,PlayViewDelegate {
    
    var count: Int = 0
    
    fileprivate var playView: HRPlayView!
    fileprivate var imageName: String = ""
    fileprivate var player: AVPlayer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 防止其他ViewController的导航被遮挡, 这个类的主要作用是 PlayView
        isNavigationBarHidden = true
        // 开启两个通知接收(HRMeViewController传入)
        NotificationCenter.default.addObserver(self, selector: #selector(hidePlayView), name: NSNotification.Name(rawValue: "hidePlayView"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(showPlayView), name: NSNotification.Name(rawValue: "showPlayView"), object: nil)
        // 开启一个通知接受,播放URL 及图片
        NotificationCenter.default.addObserver(self, selector: #selector(playing(_:)), name: NSNotification.Name(rawValue: "BeginPlay"), object: nil)
        playView = HRPlayView()
        playView.delegate = self
        view.addSubview(self.playView)
        playView.snp.makeConstraints({(make) in
            make.bottom.equalTo(0)
            make.centerX.equalTo(UIScreen.main.bounds.size.width / 2)
            make.width.equalTo(65)
            make.height.equalTo(70)
        })
    }
    
    deinit {
        // 关闭消息中心
        NotificationCenter.default.removeObserver(self)
    }
    
    // 隐藏图片
    func hidePlayView(_ notification: Notification) {
        playView.isHidden = true
    }
    // 显示图片
    func showPlayView(_ notification: Notification) {
        playView.isHidden = false
    }
    
    /** 通过播放地址 和 播放图片 */
    func playing(_ notification: Notification) {
        
        
        // 设置背景图
        if let coverURL = notification.userInfo?["coverURL"] as? URL {
            playView.contentIV.setImageWith(coverURL)
        }
        
        guard let musicURL = notification.userInfo?["musicURL"]  as? URL else { return }

        
        // 支持后台播放
        try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        // 激活
        try? AVAudioSession.sharedInstance().setActive(true)

        // 开始播放
        player = AVPlayer(url: musicURL)
        player?.play()
    }
    
    // MARK: - PlayView的代理方法
    func playButtonDidClick(_ selected: Bool) {
        // 按钮被点击方法, 判断按钮的selected状态
        if selected {
            self.player?.play()
            // 继续播放
        }
        else {
            self.player?.pause()
            // 暂停播放, 以后会取消, 此处应该是跳转最后一个播放器控制器
        }
    }
    
}
